<template>
  <div class="app-container">
    <el-container>
      <!--户型数据-->
      <el-main style="padding: 0 0 0 20px;">
        <div style="display: flex">
          <header-select style="margin-right: 10px;" @selectProject="getProject" />
          <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item size="mini" label="" prop="postCode">
              <el-input
                v-model="queryParams.layoutName"
                placeholder="请输入户型名称/结构"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item size="mini">
              <el-button icon="el-icon-plus" type="primary" @click="addRecord()">新增</el-button>
              <el-button icon="el-icon-plus" type="primary" :disabled="multipleSelection.length < 1" @click="copy()">复制户型
              </el-button>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 表格数据 -->
        <el-table
          ref="Table"
          v-loading="loading"
          highlight-current-row
          size="small"
          :data="dataList"
          height="calc(100vh - 150px)"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column label="序号" type="index" width="50" align="center">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="户型名称" align="center" min-width="100">
            <template slot-scope="scope">
              <el-popover placement="top-start" trigger="click">
                <div class="check-edit-content">{{ scope.row.layoutName }}</div>
                <div slot="reference" class="ellipsis">{{ scope.row.layoutName }}</div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="户型结构" align="center" min-width="90">
            <template slot-scope="scope">
              <el-popover placement="top-start" trigger="click">
                <div class="check-edit-content">{{ scope.row.layoutStruct }}</div>
                <div slot="reference" class="ellipsis">{{ scope.row.layoutStruct }}</div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="装修标准" align="center" prop="decorationType">
            <template slot-scope="scope">
              {{ showRoomType(scope.row.decorationType) }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="检查部位" align="center">
            <template slot-scope="scope">
              {{ showRoomSpace(scope.row.roomSpaceListMap) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="openDrawPlane(scope.row)">绘制部位</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新增修改 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="800px"
      @close="dialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div class="form-content">
          <div class="form-left">
            <el-form-item label="户型名称" prop="layoutName">
              <el-input v-model="form.layoutName" placeholder="请输入户型名称" />
            </el-form-item>
            <el-form-item label="户型结构" prop="layoutStruct">
              <el-input v-model="form.layoutStruct" placeholder="请输入户型结构" />
            </el-form-item>
          </div>
          <div class="form-right">
            <el-form-item label="装修标准" prop="decorationType">
              <el-select v-model="form.decorationType" style="width: 100%;" placeholder="请选择">
                <el-option
                  v-for="item in decorationOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
              <!-- <el-input v-model="form.decorationType" placeholder="请输入装修标准" /> -->
            </el-form-item>
          </div>
        </div>
        <div>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" rows="4" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="检查部位" prop="roomSpaceList">
            <el-transfer
              v-model="form.roomSpaceList"
              style="text-align: left;"
              filterable
              :left-default-checked="[2, 3]"
              :right-default-checked="[1]"
              :render-content="renderFunc"
              :titles="['待选项', '已选项']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
              :data="positionOptions"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="户型图片" prop="fileIds">
            <el-upload
              ref="upload"
              :limit="10"
              class="plan-upload-btn"
              :before-upload="beforeUpload"
              name="file"
              :multiple="true"
              accept=".png, .jpg, .jpeg"
              action="string"
              list-type="picture-card"
              :http-request="UploadImage"
              :file-list="fileManage.showFileList"
              :on-remove="fileRemove"
              :on-preview="handlePictureCardPreview"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="dialogLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog :visible.sync="fileManage.openPreview" top="5vh">
      <img width="100%" style="height: 80vh;" :src="fileManage.previewUrl" alt="">
    </el-dialog>
    <!-- <draw-floor-plan :show.sync="showDrawWindow" /> -->
    <!-- 图形绘制 -->
    <el-dialog title="绘制部位" width="60%" :visible.sync="showDrawWindow" :close-on-click-modal="false" :before-close="detectClose">
      <canvas-draw
        v-if="showDrawWindow"
        :position-list="layoutOptions"
        :layout-id="layoutId"
        :curproject-id="queryParams.curprojectId"
        :close-dialog="closeDialog"
        @colse="onClose"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  addLayout,
  copyLayout,
  delLayout,
  listLayout,
  updateLayout,
  uploadPicture
} from '@/api/baseManage/layoutManage'
import {
  listRoomSpace
} from '@/api/qualityManage/roomSpace'
import HeaderSelect from '../../statement/components/HeaderSelect'
import {
  getToken
} from '@/utils/auth'
import {
  listData
} from '@/api/system/dict/data'
  // import DrawFloorPlan from './DrawFloorPlan'
import CanvasDraw from './moudles/canvasDraw'
export default {
  name: 'HouseType',
  components: {
    HeaderSelect,
    CanvasDraw
    // DrawFloorPlan
  },
  data() {
    return {
      /* 当前选中楼栋数据 */
      baseForm: {},
      queryParams: {
        curprojectId: '', // 项目id
        layoutName: '', // 户型名称
        pageNum: 1, // 当前页码
        pageSize: 10 // 一页显示行数
      },
      decorationOptions: [], // 装修标准
      dataList: [],
      total: 0,
      loading: false,
      dialogVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增',
        read: '查看'
      },
      form: {
        curprojectId: '',
        fid: '',
        layoutName: '',
        layoutStruct: '',
        remark: '',
        decorationType: '',
        roomSpaceList: [],
        fileIds: [] // 图片id
      },
      dialogLoading: false,
      positionOptions: [],
      // 表单校验
      rules: {
        layoutName: [{
          required: true,
          message: '户型名称不能为空',
          trigger: 'blur'
        }],
        layoutStruct: [{
          required: true,
          message: '户型结构不能为空',
          trigger: 'blur'
        }],
        decorationType: [{
          required: true,
          message: '装修标准不能为空',
          trigger: 'blur'
        }]
      },
      multipleSelection: [],
      fileManage: {
        open: false,
        uploadUrl: process.env.VUE_APP_BASE_API + '/gcxt/checktable/upload',
        extraData: {
          fid: ''
        },
        showFileList: [],
        newFileList: [],
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        openPreview: false,
        previewUrl: false
      },
      showDrawWindow: false,
      layoutOptions: [], // 绘制检查部位
      layoutId: '', // 户型Id'
      closeDialog: false
    }
  },
  created() {
    // 获取装修标准
    this.getDecorationList()
  },
  methods: {
    getProject(project) {
      this.queryParams.curprojectId = project.id
      this.getList()
    },
    getDecorationList() {
      listData({
        dictType: 'sys_decoration_type'
      }).then(response => {
        this.decorationOptions = response.rows
      })
    },
    handleSizeChange() {
      // this.currentPage,
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm('queryForm')
      this.queryParams.layoutName = ''
      this.queryParams.layoutStruct = ''
      this.handleQuery()
    },
    // 编辑框清除
    resetForm() {
      this.form = {
        curprojectId: '',
        fid: '',
        layoutName: '',
        layoutStruct: '',
        remark: '',
        decorationType: '',
        roomSpaceList: [],
        fileIds: [] // 图片id
      }
      // 清空图片
      this.fileManage.showFileList = []
      this.fileManage.newFileList = []
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      listLayout(this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    showRoomType(val) {
      const decoration = this.decorationOptions.filter(elem => {
        return elem.dictValue === val
      })
      if (decoration.length > 0) {
        return decoration[0].dictLabel
      }
    },
    showRoomSpace(item) {
      const list = []
      item.forEach(element => {
        list.push(element.FNAME_L2)
      })
      return list.join('、') || ''
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.Table.clearSelection()
        this.$refs.Table.toggleRowSelection(val.pop())
      }
      this.multipleSelection = val
    },
    // 新增记录
    addRecord() {
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.getPosition()
    },
    // 获取部位信息
    getPosition() {
      if (this.positionOptions.length < 1) {
        listRoomSpace(this.positionQuery).then(response => {
          const list = []
          response.data.forEach(elem => {
            list.push({
              key: elem.fid,
              label: elem.fnameL2,
              disabled: false
            })
          })
          this.positionOptions = list
        })
      }
    },
    // 复制记录
    copy() {
      const params = {
        layoutId: this.multipleSelection[0].fid
      }
      copyLayout(params).then(response => {
        this.handleQuery()
      })
    },
    submitForm() {
      this.dialogLoading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let params = this.form
          if (this.fileManage.newFileList.length > 0) {
            let i = 0
            this.fileManage.newFileList.forEach(async(elem) => {
              const response = await uploadPicture(elem)
              this.form.fileIds.push(response.data)
              ++i
              if (i === this.fileManage.newFileList.length) {
                params = this.form
                this.saveData(params)
              }
            })
          } else {
            this.saveData(params)
          }
        }
      })
    },
    saveData(params) {
      if (this.dialogStatus === 'create') {
        // 新增
        params.curprojectId = this.queryParams.curprojectId
        addLayout(params).then(response => {
          this.dialogLoading = false
          this.dialogVisible = false
          this.handleQuery()
        })
      } else if (this.dialogStatus === 'update') {
        // 编辑
        updateLayout(params).then(response => {
          this.dialogLoading = false
          this.dialogVisible = false
          this.handleQuery()
        })
      }
    },
    cancel() {
      this.dialogVisible = false
    },
    dialogClose() {
      this.resetForm()
    },
    // 修改
    handleUpdate(row) {
      this.getPosition()
      this.form = Object.assign({}, row)
      const list = []
      row.roomSpaceListMap.forEach(elem => {
        list.push(elem.fid)
      })
      this.form.roomSpaceList = list
      if (this.form.fileIds.length > 0) {
        this.form.fileIds.forEach(id => {
          this.fileManage.showFileList.push({
            url: process.env.VUE_APP_BASE_API + '/file/download?fileKey=' + id,
            fid: id
          })
        })
      }
      // this.this.fileManage
      this.dialogStatus = 'update'
      this.dialogVisible = true
    },
    // 删除
    handleDelete(row) {
      const params = [row.fid]
      this.$confirm('此操作将永久删除该条数据 , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delLayout(params).then(response => {
          this.handleQuery()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    renderFunc(h, option) {
      // return <span> { option.label } </span>
      return <span> { option.label } </span>
    },
    handleChange(value, direction, movedKeys) {
    },
    /* 上传之前过滤 */
    beforeUpload(file) {
      const file_type = file.type
      const isLt2M = file.size / 1024 / 1024 < 2

      const accept_type = ['image/jpeg', 'image/png', 'image/jpg']
      const accept = accept_type.includes(file_type)
      if (!accept) {
        this.msgError('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.msgError('上传图片大小不能超过 2MB!')
        return false
      }
      return accept && isLt2M
    },
    /* 上传成功*/
    handleUploadSuccess(response, file, fileList) {
      if (response.code !== 200) {
        if (response.code === 401) {
          this.$confirm('登录状态已过期，请重新登录', '系统提示', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            showClose: false,
            closeOnClickModal: false,
            showCancelButton: false,
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('LogOut').then(() => {
              location.href = '/index'
            })
          })
        } else {
          // 上传文件失败 则抛出错误信息
          this.msgError('上传文件失败 ' + response.msg)
        }
        for (let i = 0; i < fileList.length; i++) {
          if (file.name === fileList[i].name) {
            fileList.splice(i, 1)
          }
        }
        return
      }
      // 存储图片id
      this.form.fileIds.push(response.data)
      file.fid = response.data
    },
    // 预览
    handlePictureCardPreview(file) {
      this.fileManage.previewUrl = file.url
      this.fileManage.openPreview = true
    },
    // 图片删除
    fileRemove(file, fileList) {
      const index = this.form.fileIds.indexOf(file.fid)
      if (index !== -1) {
        this.form.fileIds.splice(index, 1)
      }
    },
    openDrawPlane(row) {
      if (row.roomSpaceListMap.length < 1) {
        this.$message.warning(`当前户型不存在检查部位`)
        return
      }
      if (row.fileIds.length < 1) {
        this.$message.warning(`请先上传户型图片`)
        return
      }
      this.layoutId = row.fid
      this.layoutOptions = row.roomSpaceListMap
      this.showDrawWindow = true
    },
    detectClose() {
      this.closeDialog = true
    },
    onClose(val) {
      this.closeDialog = false
      if (val) {
        this.layoutId = ''
        this.showDrawWindow = false
        this.handleQuery()
      }
    },
    UploadImage(e) {
      const formData = new FormData()
      formData.append('fid', '')
      formData.append('file', e.file)
      this.fileManage.newFileList.push(formData)
    }
  }
}

</script>

<style lang='scss' scoped>
  /deep/ thead .el-table-column--selection .cell {
    display: none;
  }

  /deep/ .select-project>div {
    align-items: center;
  }

  /deep/ .el-transfer__buttons button {
    display: block;
    margin-left: 0px;
    padding: 10px;
    border-radius: 50%;
  }

  /deep/ .el-transfer-panel {
    width: 292px;
  }

  .form-content {
    display: flex;
    align-items: flex-start;

    .form-left {
      flex: 1;
    }

    .form-right {
      flex: 1;
    }
  }

</style>
